<template>
  <div>
    <div
      class="dioa-center flex items-center w-full h-31 border border-neutral-30 py-8 px-10 justify-between rounded-lg"
    >
      <div class="dioa-center flex justify-center items-center">
        <div class="dioa-box">
          <div class="dioa-box font-medium text-2xl">
            <h1 class="title">发票中心</h1>
          </div>
          <p class="dioa-text"></p>
        </div>
      </div>
      <div class="dioa-center flex justify-center items-center space-x-5">
        <button
          type="button"
          @click="makeInvoice()"
          class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-10 px-5 text-base font-medium text-black bg-neutral-30 hover:bg-neutral-40 active:bg-black active:text-white disabled:text-neutral-40 disabled:bg-neutral-30 data-loading:text-transparent data-loading:bg-neutral-30 rounded-full border-0"
        >
          批量开票
        </button>

        <router-link to="/user/ticketHeader">
          <button
            type="button"
            class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-10 px-5 text-base font-medium text-white bg-red hover:bg-neutral-60 active:bg-black disabled:bg-neutral-40 data-loading:text-transparent data-loading:bg-neutral-40 rounded-full border-0"
          >
            开票头管理
          </button>
        </router-link>
      </div>
    </div>

    <div style="margin: 15px 0"></div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="可开票" name="0">
        <Listpage
          :tableData="okListdata"
          ref="childRef"
          @updateOpenData="receiveDataFun"
          :showtab="true"
        >
          <template #default="{ row }">
            <!-- {{ row }} -->
            <el-button class="custom-button" @click="makeInvoice(row)" size="small"
              >申请开票</el-button
            >
          </template>
        </Listpage>
      </el-tab-pane>
      <el-tab-pane label="已申请" name="1">
        <Listpage :tableData="Listdata">
          <template #default="{ row }">
            <el-tag
              :type="row.status === '0' ? 'danger' : 'success'"
              disable-transitions
              size="small"
            >
              <span v-if="row.status == '0'">等待开票</span>
              <span v-if="row.status == '1'">已开票</span>
            </el-tag>
          </template>
        </Listpage>
      </el-tab-pane>
    </el-tabs>
    <div style="margin-top: 50px">
      <Pagination
        class="pagination"
        :current-page="temparam.pageNum"
        :page-size="temparam.pageSize"
        :total="totalItems"
        @update:current-page="temparam.pageNum = $event"
        @update:page-size="pageSize = $event"
        @change="loadData(activeName, temparam)"
      />
    </div>
    <!-- 发票头抬头弹窗 -->
    <MyDialog @update:visible="updateDialog" :initVisible="dialogVisible" :width="600">
      <div class="formLayer">
        <h3 class="title">
          请选择发票抬头
          <el-button size="small" circle type="danger" @click="handleClose"
            ><el-icon><CloseBold /></el-icon
          ></el-button>
        </h3>
        <MyTable :tableData="ticketTopList" :columns="titleData">
          <template #fordata="{ row }">
            <!-- 自定义单元格内容 -->
            <!-- {{ row }} -->
            <el-button size="small" type="danger" @click="selectOpen(row)"
              >选择开具</el-button
            >
          </template>
        </MyTable>
      </div>
    </MyDialog>
    <!-- end -->
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import type { TabsPaneContext } from "element-plus";
import { orderListProps, ticketTopProps } from "@/common/utils/userType";
import Pagination from "@/components/Pagination.vue";
import Listpage from "@/components/Listpage.vue";
import {
  getOrderInvoiceList,
  getPageList,
  getinvoicelist,
  getApplyInvoice,
} from "@/common/userApi";
import MyDialog from "@/components/MyDialog.vue";
import MyTable from "@/components/MyTable.vue";
import { ElMessage } from "element-plus";

const activeName = ref("0");

// 获取可开票数据okListdata
const okListdata = ref<orderListProps[] | any>([]);
const Listdata = ref<orderListProps[] | any>([]); //已申请
// let currentPage = ref(1);
// let pageSize = ref(5);
let totalItems = ref(0); // 假设总数为100
// 加载数据的逻辑
let temparam = reactive({
  pageNum: 1,
  pageSize: 5,
});
function loadData(id: string, data?: any) {
  let url = ref<any>(null);
  window.scrollTo(0, 0);
  if (activeName.value == "0") {
    let temp = {
      payFlag: 1,
      invoiceStatus: 0,
    };
    data = { ...data, ...temp };
    url.value = getPageList(data);
  } else {
    url.value = getOrderInvoiceList(data);
  }
  url.value.then((res) => {
    const tempTotal = res.total + "";
    totalItems.value = parseInt(tempTotal);
    if (activeName.value == "0") {
      okListdata.value = res.rows;
    } else {
      Listdata.value = res.rows;
    }
  });
}
// 初始化数据
loadData("0", temparam);
// 点击数据加载
const handleClick = (tab: TabsPaneContext) => {
  temparam.pageNum = 1;
  activeName.value = tab.paneName;
  loadData(activeName, temparam);
};
// 申请开票
const dialogVisible = ref(false);
const ticketTopList = ref<ticketTopProps[] | any>([]);
const titleData = [
  { label: "发票类型", prop: "fpType", width: 120 },
  { label: "抬头类型", prop: "ttType", width: 120 },
  { label: "发票抬头", prop: "fpTitel", width: 120 },
  { label: "操作", type: "template" },
];
// 定义申请开票列表的参数对象
let openTicket = reactive({
  invoiceAmount: "",
  invoiceInfoId: null,
  orderIds: [],
});
// 下面两个方法是发票弹窗对应的事件
const updateDialog = (value) => {
  dialogVisible.value = value;
};
const handleClose = () => {
  dialogVisible.value = false;
  // receiveData.value = [];
};
// 开票
const childRef = ref(null);
const receiveData = ref<orderListProps[]>([]); //接收子组件传过来的数据
const receiveDataFun = (data: any) => {
  receiveData.value = data;
};

const makeInvoice = (item?) => {
  if (childRef.value && item) {
    childRef.value.handleSelectionChange(item);
    childRef.value.toggleSelection(item);
  }
  if (receiveData.value.length == 0) {
    ElMessage.error("请选择您要开票的订单");
  } else {
    dialogVisible.value = true;
    let price = 0;
    let arrtemp = ref([]);
    if (receiveData.value.length > 0) {
      receiveData.value.forEach((item) => {
        price = price + item.orderAmount * 1;
        openTicket.invoiceAmount = price + "";
        arrtemp.value.push(item.id);
        openTicket.orderIds = arrtemp;
      });
    } else {
      openTicket.invoiceAmount = receiveData.value.orderAmount;
      openTicket.orderIds = [receiveData.value.id];
    }

    let data = reactive({
      pageNum: 1,
      pageSize: 100,
    });
    getinvoicelist(data).then((res) => {
      ticketTopList.value = res.data;
    });
  }
};
// 选择开具发票getApplyInvoice
const selectOpen = (item) => {
  openTicket.invoiceInfoId = item.id;
  getApplyInvoice(openTicket).then((res) => {
    if (res.data) {
      ElMessage({
        message: "发票已申请成功，请注意查收邮件！",
        type: "success",
      });
      loadData(activeName, temparam);
    } else {
      ElMessage.error(res.msg);
    }
    handleClose();
  });
};
</script>
<style lang="scss">
.title {
  font-size: 20px;
  font-weight: bold;
  padding: 10px 0 30px;
}
.el-button--danger {
  background: #d01c1b !important;
}
.el-button--text {
  color: #d01c1b !important;
}

.orders-page {
  max-width: 1200px;
  margin: 0 auto;
}

/* 改变Checkbox未选中状态的背景颜色 */
// .el-checkbox__inner {
//   border-color: #000 !important; /* 蓝色 */
// }

/* 改变Checkbox选中状态的背景颜色 */
.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #d01c1b; /* 绿色 */
}
.el-checkbox__input.is-checked .el-checkbox__inner:after {
  border-color: #fff !important;
}
.el-checkbox__input.is-checked .el-checkbox__inner,
.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  border-color: #d01c1b !important;
}
.el-tabs__item.is-active,
.el-tabs__item:hover {
  color: #d01c1b;
}
.el-tabs__active-bar {
  background-color: #d01c1b;
}
.el-checkbox__input.is-checked .el-checkbox__inner,
.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #d01c1b;
}
.formLayer {
  padding: 20px;
  h3 {
    display: flex;
    justify-content: space-between;
  }
}
</style>
